package com.wyz.tracing.utils;

import com.wyz.tracing.domain.entity.base.Aggregate;
import com.wyz.tracing.domain.entity.base.Identifier;

import java.io.*;
/**
 * @author wyz
 * @version 1.0
 * @date 2023/8/15
 */
public class SnapshotUtils {

    /**
     * 快照
     *
     * @param aggregate
     * @param <T>
     * @param <ID>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T extends Aggregate<ID>, ID extends Identifier> T snapshot(T aggregate) throws IOException, ClassNotFoundException {
//        ObjectMapper objectMapper = new ObjectMapper();
//        String json = objectMapper.writeValueAsString(aggregate);
//        T snapshot = (T) objectMapper.readValue(json, aggregate.getClass())

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(aggregate);

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        T snapshot = (T) objectInputStream.readObject();

        objectOutputStream.close();
        byteArrayOutputStream.close();

        objectInputStream.close();
        byteArrayInputStream.close();
        return snapshot;
    }
}
